package com.gongj.apppay.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

public class RestTemplateUtil {

    @Autowired
    @Qualifier("restTemplateBean")
    RestTemplate restTemplate;

    public void sendMapPost(String url, Map<String,Object> map){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        //需要将Map转换为MultiValueMap 不然会出现:No HttpMessageConverter for java.util.HashMap and content type "application/x-www-form-urlencoded"
        MultiValueMap<String, Object> stringObjectMultiValueMap = new LinkedMultiValueMap<>();
        for (Map.Entry<String,Object> m : map.entrySet()){
            stringObjectMultiValueMap.add(m.getKey(),m.getValue());
        }
        HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(stringObjectMultiValueMap,httpHeaders);
        ResponseEntity<String> exchange = restTemplate.exchange(url, method, httpEntity, String.class);
        System.out.println(exchange.getBody());
    }
}
